/**
 * 
 */
package server.alarmThreads;


import java.io.IOException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.Scanner;

import org.apache.log4j.Logger;

import server.config.ServerConfig;
import server.container.SMSAlamierung;
import server.db.SQL;


/**
 * @author Christian
 * 
 */
public class SMSVersaender {
	
	private static Logger logger = Logger.getLogger(SMSVersaender.class);
	
	public SMSVersaender() {

	}

	
	public boolean sendSMS(SMSAlamierung smsAlarmierung) {

		long t1 = System.currentTimeMillis();
		String nummer = smsAlarmierung.getNummer();
		nummer = nummer.replaceAll(" ", "");
		logger.trace("Alarmieren von " + nummer);
		String url = "";
		StringBuilder logBuilder = new StringBuilder();
		Scanner scanner = null;
		boolean sendenOK = false;
		try {
			
			double geschaetzterKontoStand = smsAlarmierung.getKontostandDouble() - 0.1;
			
			NumberFormat nf = NumberFormat.getInstance();
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(2);
			
			//Strings Escapen
			String message = URLEncoder.encode(smsAlarmierung.getAlarm().toString() + " " +
							" Kontostand: ~" + nf.format(geschaetzterKontoStand), "UTF-8");
			String absender =  URLEncoder.encode(smsAlarmierung.getAbsender(), "UTF-8");
			url = "https://gateway.smstrade.de/?key="+ServerConfig.getInstance().getSMSKey()+"&to=" + nummer + "&"
					+ "message=" + message + "&route=" + smsAlarmierung.getSMSMode()
					+ "&from=" + absender + "&dlr=1&messsage_id=1&ref=" + smsAlarmierung.getUserId() + "&cost=1&debug=";
			if (ServerConfig.getInstance().isDebug()) {
				url += "1";
			} else {
				url += "0";
			}
			
			System.out.println(url);
			
			logBuilder.append("\n");
			logBuilder.append("--------SMS-Alarm--------\n");
			logBuilder.append("Nummer: ");
			logBuilder.append(nummer);
			logBuilder.append("\n");
			logBuilder.append("\n");
			logBuilder.append(url);
			logBuilder.append("\n");
			URL con = new URL(url);
			scanner = new Scanner(con.openStream());
			
			while (scanner.hasNext()) {
				String part = scanner.nextLine();
				if (part.startsWith("0")) {
					try {
						Double.parseDouble(part);
						SQL.getInstance().addKosten(nummer, part);
					} catch (NumberFormatException e) {
						logger.error("Kostenfehler: " + part);
					}
				}
				if (part.equals("10")) {
					SQL.setNumberInValid(smsAlarmierung);
					logger.debug("Nummer ungültig " + nummer);
					sendenOK = true;
				}
			
				if (part.equals("100")) {
					sendenOK = true;
				}
				if (!part.equals("")) {
					logger.debug(part);
					logBuilder.append(part);
					logBuilder.append("\n");
				}
			}
			
			logBuilder.append(System.currentTimeMillis() - t1 + "ms");
			
			logBuilder.append("----ENDE-SMS----");
			logger.info(logBuilder.toString());
			
		} catch (IOException e) {
			
			logger.error("SMS-Fehler" + url, e);
		} finally {
			if(scanner != null) {
				scanner.close();
			}
			
		}
		
		return sendenOK;
	}
}
